package com.nova.android.tvlauncher.ui.fragment.atv

import android.content.ComponentName
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.provider.Settings
import android.view.KeyEvent
import android.view.View
import android.view.View.INVISIBLE
import android.view.View.VISIBLE
import android.widget.ImageView
import androidx.core.view.isVisible
import androidx.core.view.postDelayed
import androidx.leanback.widget.BaseGridView
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.RecyclerView
import com.nova.android.tvlauncher.AppCache
import com.nova.android.tvlauncher.R
import com.nova.android.tvlauncher.constants.ConstantsAtv
import com.nova.android.tvlauncher.constants.ConstantsAtv.PACKAGE_NAME_PERMISSION_MANAGE
import com.nova.android.tvlauncher.constants.ConstantsAtv.REFRESH_FAVORITE_APPS
import com.nova.android.tvlauncher.constants.ConstantsAtv.REMOVE_FAVORITE_APPS
import com.nova.android.tvlauncher.databinding.FragmentAppListAtvBinding
import com.nova.android.tvlauncher.databinding.ItemApplistChildAtvBinding
import com.nova.android.tvlauncher.ext.toggle16to9Scale
import com.nova.android.tvlauncher.ui.dialog.ext.showHomeMenuDialog
import com.shudong.lib_base.ext.appContext
import com_github_lib_base.base.BaseVMFragment
import com_github_lib_base.base.BaseViewModel
import com_github_lib_base.bean.FavoriteApp
import com_github_lib_base.currentActivity
import com_github_lib_base.ext.clickNoRepeat
import com_github_lib_base.ext.createDrawable
import com_github_lib_base.ext.dimenValue
import com_github_lib_base.ext.getFavoriteAppByPackageName
import com_github_lib_base.ext.getLaunchableApps
import com_github_lib_base.ext.isAppUninstallable
import com_github_lib_base.ext.isBanner
import com_github_lib_base.ext.openApp
import com_github_lib_base.ext.rv.addModels
import com_github_lib_base.ext.rv.models
import com_github_lib_base.ext.rv.removeModelAt
import com_github_lib_base.ext.rv.setup
import com_github_lib_base.ext.uninstallPackage
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import observeLiveEvent
import sendLiveEventData


class AppListAtvXintuFragment : BaseVMFragment<FragmentAppListAtvBinding, BaseViewModel>() {


    fun reqGetFocus(){
        mBind.rvHome.apply {
            postDelayed({
                requestFocus()
            },300)
        }

    }



    override fun initObserver() {
        observeLiveEvent<String>(ConstantsAtv.APP_UNINSTALLED) {packageName ->
            //应用被卸载
            val list = (mBind.rvHome.models)as MutableList<FavoriteApp>
            val index = list.indexOfFirst { it.packageName == packageName }
            var appInfo: FavoriteApp?=null
            if(index!=-1){
                mBind.rvHome.removeModelAt(index) // 删除数据
                val favouriteApps = AppCache.favoriteAppList
                for (i in favouriteApps.size - 1 downTo 0) {
                    if (favouriteApps[i].packageName == packageName) {
                        appInfo = favouriteApps[i]
                        favouriteApps.removeAt(i)
                        break
                    }
                }
                AppCache.favoriteAppList = favouriteApps
                if(appInfo!=null){
                    sendLiveEventData(REMOVE_FAVORITE_APPS,appInfo)
                }
            }
        }
        observeLiveEvent<String>(ConstantsAtv.APP_INSTALLED) {packageName ->
            //应用被安装
            val list = (mBind.rvHome.models)as MutableList<FavoriteApp>
            val index = list.indexOfFirst { it.packageName == packageName }
            if(index==-1){
                packageName.getFavoriteAppByPackageName()?.let {
                    mBind.rvHome.addModels(mutableListOf(it),animation = true)
                }

            }
        }


        observeLiveEvent<Boolean>(ConstantsAtv.REFRESH_CHANNEL_LIST) {
            val list = (mBind.rvHome.models)as MutableList<FavoriteApp>
            val apps = appContext.getLaunchableApps().toMutableList()
            list.updateFavoriteAppsOnResume(apps,mBind)
        }

    }

    fun MutableList<FavoriteApp>.updateFavoriteAppsOnResume(
        latestApps: MutableList<FavoriteApp>,
        binding: FragmentAppListAtvBinding // 替换为实际的 binding 类型
    ) {
        // 获取最新的包名集合
        val latestPackageNames = latestApps.map { it.packageName }.toSet()
        // 获取当前收藏列表的包名集合
        val currentPackageNames = this.map { it.packageName }.toSet()

        // 如果两个集合完全相同，无需处理
        if (latestPackageNames == currentPackageNames) {
            return
        }

        // 处理卸载操作：移除当前列表中不存在于最新列表的应用
        for (i in size - 1 downTo 0) {
            val packageName = this[i].packageName
            if (packageName !in latestPackageNames) {

                binding.rvHome.removeModelAt(i)
                val favouriteApps = AppCache.favoriteAppList
                val index = favouriteApps.indexOfFirst { it.packageName == packageName }
                if(index!=-1){

                    val appInfo = favouriteApps[index]
                    favouriteApps.removeAt(index)
                    AppCache.favoriteAppList = favouriteApps
                    sendLiveEventData(REMOVE_FAVORITE_APPS,appInfo)

                }


            }
        }

        // 处理安装操作：添加最新列表中不在当前列表的应用
        latestApps.forEach { favoriteApp ->
            if (favoriteApp.packageName !in currentPackageNames) {
                binding.rvHome.addModels(mutableListOf(favoriteApp), animation = true)
            }
        }
    }

    override fun initView() {
        val apps = appContext.getLaunchableApps().toMutableList()

        /*mBind.rvHome.setWindowAlignment(BaseGridView.WINDOW_ALIGN_BOTH_EDGE);
        mBind.rvHome.setWindowAlignmentOffset(com.codeZeng.lib_dimen.R.dimen.qb_px_50.dimenValue());
        mBind.rvHome.setWindowAlignmentOffsetPercent(0f);
        mBind.rvHome.setItemAlignmentOffsetPercent(0f);*/
        mBind.rvHome.setNumColumns(6)
        mBind.rvHome.setItemSpacing(com.codeZeng.lib_dimen.R.dimen.qb_px_15.dimenValue())
        mBind.rvHome.setup(
           apps
        ) {
            addType(FavoriteApp::class, R.layout.item_applist_child_atv)
            onBind {

                    val itemBinding = getBinding<ItemApplistChildAtvBinding>()
                    val item = getModel<FavoriteApp>()

                    itemBinding.tvAppName.text = item.displayName
                    val drawable = item.createDrawable(appContext)
                    if (drawable.isBanner()) {
                        // 横屏 Banner 的处理逻辑
                        itemBinding.ivBigicon.scaleType = ImageView.ScaleType.FIT_CENTER
                        itemBinding.ivBigicon.setImageDrawable(drawable)
                        itemBinding.ivIcon.isVisible = false
                        itemBinding.ivBigicon.isVisible = true
                    } else {
                        // Icon 的处理逻辑
                        itemBinding.ivIcon.setImageDrawable(drawable)
                        itemBinding.ivIcon.isVisible = true
                        itemBinding.ivBigicon.isVisible = false
                    }

                    itemBinding.rlAppsIcon.setOnFocusChangeListener { _, hasFocus ->
                        itemBinding.rlAppsIcon.toggle16to9Scale(modelPosition%6 == 0, hasFocus,1.25f)
                        if (hasFocus) itemView.elevation = 10f else itemView.elevation =
                            0f
                        itemBinding.tvAppName.visibility = if (hasFocus) VISIBLE else INVISIBLE
                        itemBinding.tvAppName.isSelected = hasFocus
                    }

                    itemBinding.rlAppsIcon.clickNoRepeat {
                        if (item.packageName == "com.android.tv.settings") {
                            currentActivity?.let { // 跳转到系统设置页面
                                //startActivity(Intent(Settings.ACTION_SETTINGS)) }
                                val intent = Intent().apply {
                                    component = ComponentName(
                                        "com.android.tv.settings",  // 目标包名
                                        "com.android.tv.settings.MainSettings"  // 目标Activity类名
                                    )
                                }
                                it.startActivity(intent)
                            }
                        } else {
                            item.packageName.openApp()
                        }

                    }

                itemBinding.rlAppsIcon.setOnKeyListener { view, keyCode, event ->
                    if (keyCode == KeyEvent.KEYCODE_MENU && event.action == KeyEvent.ACTION_DOWN) {
                        val favouriteApps = AppCache.favoriteAppList
                        val isExist = favouriteApps.any { it.packageName == item.packageName }
                        showPopup(view, item, modelPosition, isExist, mBind.rvHome)
                        true
                    } else false
                }

                    itemBinding.rlAppsIcon.setOnLongClickListener {
                        val favouriteApps = AppCache.favoriteAppList
                        val isExist = favouriteApps.any { it.packageName == item.packageName }
                        showPopup(it, item, modelPosition, isExist, mBind.rvHome)
                        true
                    }
                }

        }

        mBind.rvHome.setOnChildSelectedListener { _, _, position, _ ->
            positionChangeJob?.cancel() // 取消旧的延迟任务
            positionChangeJob = lifecycleScope.launch {
                delay(POSITION_DELAY)
                // 判断是否需要执行逻辑
                val isCurrentInRange = position in 0..5
                val wasLastInRange = lastSelectedPosition in 0..5

                if (isCurrentInRange) {
                    // 仅当上一次不在 0..5 范围内时才调用 showTopView
                    if (!wasLastInRange) {
                        (parentFragment as AppsAtvXintuFragment).showTopView()
                        (parentFragment as? AppsAtvXintuFragment)?.setListFragmentFullHeight(false)
                    }
                } else {
                    // 无论上一次是否在范围内，均需隐藏（避免状态不一致）
                    (parentFragment as AppsAtvXintuFragment).hideTopView()
                    (parentFragment as? AppsAtvXintuFragment)?.setListFragmentFullHeight(true, true)
                }

                // 更新上一次选中的位置
                lastSelectedPosition = position
            }
        }



    }

    private var positionChangeJob: Job? = null
    private val POSITION_DELAY = 100L // 延迟 100ms 确保最后状态

    // 在类中定义变量记录上一次选中的位置
    private var lastSelectedPosition = -1

    private fun showPopup(
        view: View, appInfo: FavoriteApp,
        modelPosition: Int,
        isExist: Boolean,
        rvApps: RecyclerView,
    ) {
        view.showHomeMenuDialog {

            isFavorited = isExist
            isInfoUninstallVisible = true
            if(requireActivity().isAppUninstallable(appInfo.packageName)) {
                isDisableUninstall = false
            }else {
                isDisableUninstall = true
            }

            clickOpen {
                appInfo.packageName.openApp()
            }
            clickMove {
                //ToastUtils.show("移动")
            }
            clickRemove { isFavorited ->
                if(isFavorited) {

                    val favouriteApps = AppCache.favoriteAppList
                    for (i in favouriteApps.size - 1 downTo 0) {
                        if (favouriteApps[i].packageName == appInfo.packageName) {
                            favouriteApps.removeAt(i)
                            break
                        }
                    }
                    AppCache.favoriteAppList = favouriteApps
                    sendLiveEventData(REMOVE_FAVORITE_APPS, appInfo)
                }else {
                    val favouriteApps = AppCache.favoriteAppList
                    favouriteApps.add(appInfo)
                    AppCache.favoriteAppList = favouriteApps
                    sendLiveEventData(REFRESH_FAVORITE_APPS, appInfo)
                }

            }
            clickAppInfo {
                // 跳转到应用信息页面
                PACKAGE_NAME_PERMISSION_MANAGE.openApp(pkName = appInfo.packageName)
            }

            clickUninstall {
                val success = requireActivity().uninstallPackage(appInfo.packageName)
                if(success) {
                    rvApps.removeModelAt(modelPosition) // 删除数据
                    val favouriteApps = AppCache.favoriteAppList
                    for (i in favouriteApps.size - 1 downTo 0) {
                        if (favouriteApps[i].packageName == appInfo.packageName) {
                            favouriteApps.removeAt(i)
                            sendLiveEventData(REMOVE_FAVORITE_APPS,appInfo)
                            break
                        }
                    }
                    AppCache.favoriteAppList = favouriteApps

                }
            }
        }
    }

    companion object {

        @JvmStatic
        fun newInstance() =
            AppListAtvXintuFragment().apply {
                arguments = Bundle().apply {

                }
            }
    }
}


